import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import 'dart:async';

Effect<UserRegisterViewState> buildEffect() {
  return combineEffects(<Object, Effect<UserRegisterViewState>>{
    UserRegisterViewAction.action: _onAction,
    UserRegisterViewAction.onSubmit: _onSubmit,
  });
}

void _onAction(Action action, Context<UserRegisterViewState> ctx) {}

void _onSubmit(Action action, Context<UserRegisterViewState> ctx) async {
  if (ctx.state.phoneController.text.length == 0) {
    CommonUtils.showErrorInfo(ctx.context, '请输入您的手机号');
    return;
  }

  var number = double.tryParse(ctx.state.phoneController.text);
  if (number == null) {
    CommonUtils.showErrorInfo(ctx.context, '手机号格式不支持');
    return;
  }
  else if (ctx.state.phoneController.text.length != 11) {
    CommonUtils.showErrorInfo(ctx.context, '请输入11位手机号码');
    return;
  }

  if (ctx.state.passwordController.text.length == 0) {
    CommonUtils.showErrorInfo(ctx.context, '请输入您的密码');
    return;
  }

  if (ctx.state.passwordTwoController.text.length == 0) {
    CommonUtils.showErrorInfo(ctx.context, '请输入确认密码');
    return;
  }

  if (ctx.state.passwordTwoController.text !=
      ctx.state.passwordController.text) {
    CommonUtils.showErrorInfo(ctx.context, '确认密码不一致');
    return;
  }

  CommonUtils.showWaitLoading(ctx.context);
  ResultData res = await CommonNetWork.userRegister(
    ctx.state.phoneController.text,
    ctx.state.passwordController.text,
  );
  Navigator.pop(ctx.context);
  if (res.success) {
    await CommonUtils.showAlertView(ctx.context, '注册成功!');
    Navigator.pop(ctx.context, {
      'password': ctx.state.passwordController.text,
      'mobile': ctx.state.phoneController.text,
    });
  } else {
    CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}
